<?php

namespace App\Http\Controllers;

use App\Models\Admin;

use App\Models\Basic;
use App\Models\Pay;
use App\models\Upgrade;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\User;
use DB;


class AgentController extends AdminController
{
    public function index(Request $request){

        $where=array();
        if(!empty($request->name)){
            $where[]=array("admin.name",'like',"%".$request->name."%");
        }
        if(!empty($request->email)){
            $where[]=array("admin.email",'like',"%".$request->email."%");
        }
        if(!empty($request->number)){
            $where[]=array("admin.number",'like',"%".$request->number."%");
        }
        if(!empty($request->needpay)){
            $where[]=array("admin.money",'>',"30");
            $where[]=array("admin.bankcard","!=","");
        }
        if(!empty($request->phone)){
            $where[]=array("admin.phone",'like',"%".$request->phone."%");
        }

        $list = Admin::orderBy('id','desc')->where($where)->where("type",'0')->paginate(20);

        $basic = Basic::get(['value','percent']);
        $value=array();
        $percent=array();
        foreach ($basic as $key => $val){
            $value[$key]=$val->value;
            $percent[$key]=$val->percent;
        }
//        dd($value,$percent);
//        $basic=explode(",",$basic);


        foreach ($list as $key => $val){

            $uinfo = Upgrade::where('aid',$val->id)->orderby("id","desc")->first();
            if(isset($uinfo)){
                $keys =  array_search($uinfo->money,$value)+1;
            }else{
                $keys='0';
            }
            $pinfo = Admin::where("id",$val->pid)->first();
//            dd($value[$keys]);
            if(isset($value[$keys]) && $val->totlemoney >=$value[$keys] && $pinfo->percent >= $val->percent){
                $list[$key]->upgrade='1';
            }
//            dd($list);
        }


        $append = array();
        $re = $request->toArray();
        foreach ($re as $key => $value) {
            $append[$key] = $value;
        }
        $list->appends($append);

        return view("agent.list",['data'=>$list]);

    }
    /*
        禁用
    */
    public function close($id)
    {
        $data = Admin::find($id);
        $data->act = 0;
        $data->save();
        $this->setlog(json_encode($data),'将代理 "'.$data->name.' " 禁用');

        return redirect(route('agent'));
    }
    /*
       开启
   */
    public function open($id)
    {
        $data = Admin::find($id);
        $data->act = 1;
        $data->save();
        $this->setlog(json_encode($data),'将代理 " '.$data->name.' " 禁用设置取消');

        return redirect(route('agent'));
    }
    /**
     * 交易记录
     */
    public function agentlist(Request $request , $id){
        $info = $request->user();
        if($info->id==$id){
            $sort=$info->sorts;
        }else{
            $data = Admin::find($id);
            $sort=$data->sorts;
        }

        $list = User::join("trades","trades.tranid",'=',"users.tranid")
            ->where("sorts","like",$sort."%")
            ->select("trades.*",'users.firstname','users.sorts','users.lastname','users.email','users.phone')
            ->paginate(20);
//        dd($list);

        foreach ($list as $val){
            $s = Admin::where("sorts",$val->sorts)->first();
            $val->pname= $s->name;
        }
//        dd($list);
        return view("agent.agentlist",['data'=>$list]);
    }

    public function upgrade($id){

        $info =  Admin::where("id",$id)->first();

        $basic = Basic::get(['value','percent']);
        $value=array();
        $percent=array();
        foreach ($basic as $key => $val){
            $value[$key]=$val->value;
            $percent[$key]=$val->percent;
        }

        $uinfo = Upgrade::where('aid',$id)->orderby("id","desc")->first();
        if(isset($uinfo)){
            $keys =  array_search($uinfo->money,$value) +1;
        }else{
            $keys='0';
        }

        if(isset($value[$keys]) && $info->totlemoney >=$value[$keys]){

            sort($value);
            sort($percent);
            $c=$info->totlemoney;
            $t = array_reduce($value, function($v, $w) use ($c) {
                $v = $v > $c ? $v : $w; return  $v;
            });


            $key = array_search($t,$value);

            $pinfo = Admin::where('id',$info->pid)->first(['percent']);
            if($pinfo->percent >=$percent[$key]){
                $p=$percent[$key];
            }else{
                $p= $pinfo->percent;
            }

            $upgrade = new Upgrade();
            $upgrade->aid=$id;
            $upgrade->money=$value[$key];
            $upgrade->percent=$p;
            if($upgrade->save()){
                Admin::where("id",$id)->update(["percent"=>$p]);
                $this->setlog(json_encode($upgrade),'管理员升级代理   '.$info->name);
                return redirect("/agent")->with("messages", ['0' => "升级代理成功"]);
            }else{
                return back()
                    ->withErrors(array("升级代理失败"))
                    ->withInput();
            }
        }else {
            return redirect("/agent")
                ->withErrors(array("非法进入"))
                ->withInput();

        }



    }

    public function postupgrade(Request $request){

        $id=$request->id;
        $percent = $request->percent;

        $info =  Admin::where("id",$id)->first();
        $pinfo = Admin::where("id",$info->pid)->first();

        if($percent<$info->percent || $percent >$pinfo->percent){
            return back()
                ->withErrors(array("请选择正确提成数量"))
                ->withInput();
        }else{
            $basic = Basic::where("name","UPGRADE")->first()->value;
            $basic=explode(",",$basic);
            sort($basic);
            $c=$info->totlemoney;
            $t = array_reduce($basic, function($v, $w) use ($c) {
                $v = $v > $c ? $v : $w; return  $v;
            });
            $upgrade = new Upgrade();
            $upgrade->aid=$id;
            $upgrade->money=$basic[array_search($t,$basic)];
            $upgrade->percent= $percent;
            if($upgrade->save()){
                Admin::where("id",$id)->update(["percent"=>$percent]);
                return redirect("/agent")->with("messages", ['0' => "升级代理成功"]);
            }else{
                return back()
                    ->withErrors(array("升级代理失败"))
                    ->withInput();
            }

        }


    }


    public function pay(Request $request,$id){

        if($request->isMethod("post")){
            $rets=array();
            $id=$request->id;
            $info = Admin::find($id);
                DB::beginTransaction();
                try {
                $pay = new Pay();
                $pay->aid = $id;
                $pay->befor=$info->money;
                $pay->balance_money=$request->pay;
                $pay->bankcard=$request->bankcard;
                $pay->number=$request->number;
                if($pay->save()){
//                    dd(json_encode($pay));
                   $ret =  Admin::where("id",$id)->update(['money'=>$info->money-$request->pay]);
                    if($ret){
                        $this->setlog(json_encode($pay),'给代理 "'.$info->name.' " 结算');
                        $rets=array(
                            'code'=>'success',
                            'msg'=>'处理成功'
                        );
                    }else{
                        $rets=array(
                            'code'=>'error',
                            'msg'=>'账户余额处理失败'
                        );
                    }
                }else{
                    $rets=array(
                        'code'=>'error',
                        'msg'=>'数据添加失败'
                    );
                }
                    DB::commit();
                } catch (\Exception $e) {
                    $rets=array(
                        'code'=>'error',
                        'msg'=>'账户余额处理失败'
                    );
                    //接收异常处理并回滚
                    DB::rollBack();
                }

                if($rets["code"]=='success'){
                    return redirect("/agent")->with("messages", ['0' => $rets["msg"]]);
                }else{
                    return back()
                        ->withErrors(array( $rets["msg"]))
                        ->withInput();
                }

        }else{
            $info = Admin::find($id);
            return view("agent.pay",["info"=>$info]);

        }




    }

    /**
     * @param Request $request
     * 设置用户的留存比
     */


    public function setremain(Request $request){

        $info = Admin::where(["id"=>$request->id,'remain'=>$request->val])->count();
        if($info){
            echo '2';
        }else{
            $user =  Admin::where(["id"=>$request->id])->first();
            $user->remain = $request->val;
            if($user->save()){
                $this->setlog(json_encode($user),'给用户 "'.$user->name.'" 修改留存比');
                echo 1;
            }else{
                echo 3;
            }
        }

    }

}
